package com.jhgsys.internal.sypq.controller;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.sypq.entity.Notice;
import com.jhgsys.internal.sypq.entity.Resource;
import com.jhgsys.internal.sypq.service.INoticeService;
import com.jhgsys.internal.sypq.service.IResourceService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.Random;

/**
 *  Controller
 *
 * @author ganjun
 * @date 2024-11-10 20:12:58
 */
@Slf4j
@Validated
@Controller
public class ResourceController extends BaseController {

    @Autowired
    private IResourceService resourceService;

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IDictService dictService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "resource")
    @RequiresPermissions("resource:view")
    public String resourceIndex(){
        return jumpPage("sypq/resource/resourceList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "resource/add")
    @RequiresPermissions("resource:add")
    public String resourceAdd(Model model){
        Random random = new Random();
        int randomNumber = random.nextInt(10000); // 生成0到9999之间的随机数
        String rsNo = "RS" + String.format("%04d", randomNumber); // 格式化为四位数字

        model.addAttribute("rsNo", rsNo);
        //所属人员下拉
        model.addAttribute("users", resourceService.getUsersByTenantId("0"));
        //初始化一个空对象
        model.addAttribute("resource",new Resource());
        return FebsUtil.view("sypq/resource/resourceEdit");
//        return jumpPage("sypq/resource/resourceEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "resource/update/{id}")
    @RequiresPermissions("resource:edit")
    public String resourceUpdate(Model model, @PathVariable("id") String id){
        model.addAttribute("resource", resourceService.findResourceById(id));
        //所属人员下拉
        model.addAttribute("users", resourceService.getUsersByTenantId("0"));
        return jumpPage("sypq/resource/resourceEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "resource/stop/{id}")
    @RequiresPermissions("resource:edit")
    public String resourceStop(Model model, @PathVariable("id") String id){
        model.addAttribute("resource", resourceService.findResourceById(id));
        return jumpPage("sypq/resource/resourceStop");
    }

    /**
     * 查询（所有）
     * @author ganjun
     * @date 2024-11-10 20:12:58
     */
    @GetMapping("resource")
    @ResponseBody
    @RequiresPermissions("resource:view")
    public FebsResponse getAllResources(Resource resource) {
        try {
            return success(resourceService.findResourceList(resource));
        }catch (Exception ex){
            return failure(ex);
        }

    }

    /**
     * 查询（分页）
     * @author ganjun
     * @date 2024-11-10 20:12:58
     */
    @GetMapping("resource/list")
    @ResponseBody
    @RequiresPermissions("resource:view")
    public FebsResponse resourceList(QueryRequest request, @Param("name") String name, @Param("rsPlace") String rsPlace) {
        try {
            Map<String, Object> dataTable = getDataTable(this.resourceService.findResourcePage(request, name, rsPlace));
            return success(dataTable);
        }catch (Exception ex){
            return failure(ex);
        }
    }

    /**
     * 导出资源
     * @author ganjun
     * @date 2024-11-10 20:12:58
     */
    @GetMapping("resource/export")
    @ResponseBody
    @RequiresPermissions("resource:view")
    public void export(QueryRequest request, @Param("name") String name, @Param("rsPlace") String rsPlace, HttpServletResponse response) throws FebsException {
        try {
            List<Resource> list  = resourceService.export(request, name, rsPlace);
            ExcelKit.$Export(Resource.class, response).downXlsx(list, false);
        }catch (Exception ex){
            String message = "导出Excel失败";
            log.error(message, ex);
            throw new FebsException(message);
        }
    }

    /**
     * 新增 Resource
     * @author ganjun
     * @date 2024-11-10 20:12:58
     */
    @Log("新增Resource")
    @PostMapping("resource")
    @ResponseBody
    @RequiresPermissions("resource:add")
    public FebsResponse addResource(@Valid @RequestBody Resource resource) throws FebsException {
        try {
            this.resourceService.createResource(resource);
            return success();
        } catch (Exception ex) {
            return failure(ex,"新增失败");
        }
    }

    /**
     * 逻辑删除 Resource
     * @author ganjun
     * @date 2024-11-10 20:12:58
     */
    @Log("逻辑删除Resource")
    @GetMapping("resource/delete/{id}")
    @ResponseBody
    @RequiresPermissions("resource:delete")
    public FebsResponse deleteResource(@PathVariable("id") String resourceIds) throws FebsException {
        try {
            Resource resource = new Resource();
            resource.setDeletedBy(getCurrentUser().getUserName());
            resource.setDeletedTime(new Date());
            resource.setDeletedFlg(FebsConstant.INVALID);
            this.resourceService.deleteResource(resource,resourceIds);
            return success();
        } catch (Exception ex) {
            return failure(ex,"删除失败");
        }
    }

    /**
    * 物理删除 Resource
    * @author ganjun
    * @date 2024-11-10 20:12:58
    */
    @Log("物理删除Resource")
    @GetMapping("resource/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("resource:delete")
    public FebsResponse physicallyDeleteResource(@PathVariable("id") String resourceIds) throws FebsException {
        try {
            this.resourceService.physicallyDeleteResource(resourceIds);
            return success();
        } catch (Exception ex) {
            return failure(ex,"删除失败");
        }
    }

    /**
     * 修改 Resource
     * @author ganjun
     * @date 2024-11-10 20:12:58
     */
    @Log("修改Resource")
    @PostMapping("resource/update")
    @ResponseBody
    @RequiresPermissions("resource:edit")
    public FebsResponse updateResource(@RequestBody Resource resource) throws FebsException {
        try {
            this.resourceService.updateResource(resource);
            return success();
        } catch (Exception ex) {
            return failure(ex,"修改失败");
        }
    }

    /**
     * 停用 Resource
     * @author ganjun
     * @date 2024-11-10 20:12:58
     */
    @Log("停用Resource")
    @PostMapping("resource/stop")
    @ResponseBody
    @RequiresPermissions("resource:edit")
    public FebsResponse stopResource(@RequestBody Resource resource) throws FebsException {
        try {
            resource.setRsStatus(2);
            resource.setRsStatusName(dictService.findDictLabel("RS_STATUS", "2"));
            boolean res = this.resourceService.updateResource(resource);
            //发送通知
            if(res){
                Resource r = resourceService.findResourceById(resource.getId());
                String content = "("+r.getRsName()+")于" + DateUtil.getDateFormat(r.getStopStartTime(), "yyyy-MM-dd")+"到"+DateUtil.getDateFormat(r.getStopEndTime(), "yyyy-MM-dd")+"停用，停用原因（"+r.getStopReason()+"）,请及时关注";
                Notice notice = new Notice();
                notice.setNoticeType(1);
                notice.setPendingType("资源通知");
                notice.setNoticeTitle("资源停用");
                notice.setNoticeContent(content);
                notice.setReceiveUserId("");
                notice.setReceiveRealName("");
                notice.setSendDate(new Date());
                noticeService.createNotice(notice);
            }
            return success();
        } catch (Exception ex) {
            return failure(ex,"停用失败");
        }
    }

    /**
     * 启用Resource
     * @author ganjun
     * @date 2024-11-10 20:12:58
     */
    @Log("启用Resource")
    @GetMapping("resource/start/{id}")
    @ResponseBody
    @RequiresPermissions("resource:edit")
    public FebsResponse startResource(@PathVariable("id") String resourceIds) throws FebsException {
        try {
            Resource resource = resourceService.findResourceById(resourceIds);
            resource.setStopStartTime(null);
            resource.setStopEndTime(null);
            resource.setStopReason("");
            resource.setRsStatus(3);
            resource.setRsStatusName(dictService.findDictLabel("RS_STATUS", "3"));
            boolean res = this.resourceService.updateResource(resource);
            //发送通知
            if(res){
                String content = "("+resource.getRsName()+")于"+DateUtil.getDateFormat(new Date(), "yyyy-MM-dd")+"启用，请及时关注";
                Notice notice = new Notice();
                notice.setNoticeType(1);
                notice.setPendingType("资源通知");
                notice.setNoticeTitle("资源启用");
                notice.setNoticeContent(content);
                notice.setReceiveUserId("");
                notice.setReceiveRealName("");
                notice.setSendDate(new Date());
                noticeService.createNotice(notice);
            }
            return success();
        } catch (Exception ex) {
            return failure(ex,"启用失败");
        }
    }

}
